package com.example.fszq.volleydemo1;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.example.fszq.volleydemo1.adapters.ImageSelectedAdapter;
import com.example.fszq.volleydemo1.utils.MyUtil;
import com.example.fszq.volleydemo1.utils.Parsehtml;
import com.example.fszq.volleydemo1.utils.Requesttoserver;
import com.qiniu.android.common.Zone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class DisplayMessageActivity extends AppCompatActivity {
    private String boradId = "",topId = "",forumUrl = "";
    private String nextStartUserId = "",postUserId="";
    private String replyContent = "";

    private RequestQueue quence ;
    private Requesttoserver Rserver = new Requesttoserver();
    private Parsehtml Parse = new Parsehtml();

    private TextView spage;
    private ImageView slpage,snpage,sAttach;
    private TextView sReply;
    private EditText sReplyContent;
    private GridView mGridView;
    private NumberPicker mPagePicker;
    private LinearLayout mPicLayout;
    private WebView webView;
    private Button sFirstPage,sMaxPage,sSelectCancel,sSelectOk;
    int page = 1,maxpage = 0;

    /* ----- 图片上传相关 start  ------ */
    private ImageSelectedAdapter sAdapter;
    private List<String> path = new ArrayList<>();
    private List<String> tmpPath = new ArrayList<>();
    //private List<String> uPath = new ArrayList<>();
    private static final int REQUEST_IMAGE = 2;
    private static final int REQUEST_LOGIN = 3;
    private static final int TAKE_PICTURE = 0x000001;
    private static final int CROP_PICTURE = 0x000004;
    private Map<String,String> uPath = new ConcurrentHashMap<String,String>();
    private String uFileName = "";

    private Uri imageUri;
    private File outputImage;
    /*------ 图片上传相关 end ----*/

    /*-------线程池相关 start -----*/
    private ProgressDialog mProgressDialog;
    private String TokenString = "";

    //private List<MyUploadImageThread> mTaskList = null;

    private static final int tcount = 5;
    private int i = 0;

    private static ExecutorService sTaskExe = null;
    static {
        sTaskExe = Executors.newSingleThreadExecutor();// 每次只执行一个线程任务的线程池
    }
    /** 任务是否被取消 */
    private boolean isCancled = false;

    //MyUploadImageThread task ;
    /*------线程池相关 end -------*/

    /*通用类*/
    private MyUtil myUtil = new MyUtil(this);

    private View parentView;
    private PopupWindow pop = null,popSpage = null;
    private LinearLayout ll_popup;

    /*引用回复相关*/
    String tempStr = null,quotaStr = "";


    public DisplayMessageActivity(){
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display_message);
        Intent intent = getIntent();
        String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

        parentView = getLayoutInflater().inflate(R.layout.activity_display_message, null);

        //获取boradId topId 参数
        message = message.replace(",", "");
        message = message.replace("'", "");
        int st = message.indexOf("#");
        boradId = message.substring(0, st);
        topId = message.substring(st + 1, message.length());

        //处理标题栏
        Toolbar toolbar = (Toolbar) findViewById(R.id.header_title);
        toolbar.setTitle("查看帖子");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        quence = Rserver.getRequestQueue(getApplicationContext());

        //找到webview 元素
        webView = (WebView) findViewById(R.id.web_view);
        //绑定button事件 处理访问下一页 上一页
        slpage = (ImageView)findViewById(R.id.slpage);
        snpage = (ImageView)findViewById(R.id.snpage);
        spage = (TextView)findViewById(R.id.spage);


        //初始化首页
        getPageContent();

        //处理各种页面元素的初始化
        initElement();

    }


    //初始化
    public void initElement() {


        slpage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //
                if (page == 1) {
                    page = 1;
                } else {
                    page--;
                    Log.d("lastpage", page + "");
                    getPageContent();
                }
            }
        });

        snpage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //
                if (page < maxpage) {
                    page++;
                    Log.d("nextpage", page + "");
                    getPageContent();
                }
            }
        });

        //绑定选择图片的事件
        mGridView = (GridView)findViewById(R.id.selected_view);
        mPicLayout =(LinearLayout)findViewById(R.id.selectedlayout);
        sAttach = (ImageView)findViewById(R.id.selectattach);
        sAttach.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPicLayout.getVisibility() == View.GONE) {
                    mPicLayout.setVisibility(View.VISIBLE);


                } else {
                    mPicLayout.setVisibility(View.GONE);
                }
            }
        });

        //处理选择页面的页面选择弹出框
        spage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                guickSelectPage();
            }
        });


        sReplyContent = (EditText)findViewById(R.id.replaycontent);

        //初始化图片选择提示器
        pop = new PopupWindow(DisplayMessageActivity.this);
        View view = getLayoutInflater().inflate(R.layout.selectattach_popwindow, null);

        ll_popup = (LinearLayout) view.findViewById(R.id.ll_popup);

        pop.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
        pop.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
        pop.setBackgroundDrawable(new BitmapDrawable());
        pop.setFocusable(true);
        pop.setOutsideTouchable(true);
        pop.setContentView(view);

        //RelativeLayout parent = (RelativeLayout) view.findViewById(R.id.parent);

        Button bt1 = (Button) view
                .findViewById(R.id.item_popupwindows_camera);
        bt1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                photo();
                pop.dismiss();
                ll_popup.clearAnimation();
            }
        });

        Button bt2 = (Button)view
                .findViewById(R.id.item_popupwindows_Photo);
        bt2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(DisplayMessageActivity.this, ImageSelectorActivity.class);
                startActivityForResult(intent, REQUEST_IMAGE);
//                Intent intent = new Intent();
//                intent.setAction(Intent.ACTION_PICK);
//                intent.setType("image/*");
//                DisplayMessageActivity.this.startActivityForResult(intent, REQUEST_IMAGE);
                pop.dismiss();
                ll_popup.clearAnimation();
            }
        });

        Button bt3 = (Button) view
                .findViewById(R.id.item_popupwindows_cancel);
        bt3.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                pop.dismiss();
                ll_popup.clearAnimation();
            }
        });

        //初始化图片选择gridview
        //mGridView = (MyGridView)findViewById(R.id.selected_view);
        //Log.d("origin path length",path.size()+"");
        if(path.size()==0) path.add("default");

        sAdapter = new ImageSelectedAdapter(DisplayMessageActivity.this,R.layout.image_selected_grid_item,path);
        mGridView.setAdapter(sAdapter);
        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position + 1 == path.size()) {
                    ll_popup.startAnimation(AnimationUtils.loadAnimation(DisplayMessageActivity.this, R.anim.activity_translate_in));
                    pop.showAtLocation(parentView, Gravity.BOTTOM, 0, 0);
                } else {
                    //删除已选图片
                }
            }
        });

        //初始化发送回复按钮
        sReply = (TextView)findViewById(R.id.sendreply);
        sReply.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //判断是否已经登录,若未登录需要登录
                String isLogin = myUtil.getShared("isLogin");
                Log.d("isLogin", isLogin);
                if (isLogin.equals("notlogin") || isLogin.length() == 0) {
                    Intent intent = new Intent(DisplayMessageActivity.this, UserLoginActivity.class);
                    startActivityForResult(intent, REQUEST_LOGIN);
                } else {
                    //检查是否有图片附件，有的话就上传图片
                    if (path.size() > 1) {
                        mProgressDialog = ProgressDialog.show(DisplayMessageActivity.this, null, "附件图片上传中......");
                        startUpload();
                    } else {
                        if (sReplyContent.getText().toString().length() == 0) {
                            Toast.makeText(DisplayMessageActivity.this, "回复内容不能为空", Toast.LENGTH_SHORT).show();
                        } else {
                            submitReply();
                        }
                    }
                }
            }

        });
    }

    //呼出摄像头
    public void photo() {
        //创建file对象，用于存储拍照后的图
        outputImage = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath(),"vvvv.jpg");
        //outputImage.getAbsolutePath();
        try {
            if(outputImage.exists()) {
                outputImage.delete();
            }
            outputImage.createNewFile();
        } catch(IOException e){
            e.printStackTrace();
        }
        imageUri = Uri.fromFile(outputImage);
        //Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath();
        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
        startActivityForResult(openCameraIntent, TAKE_PICTURE);
    }

    private void getPageContent() {
        if(page == 1) {
            forumUrl = "http://www.c2000.cn/dispbbs.asp?boardID=" + boradId + "&ID="  + topId + "&page=" + page;
        } else {
            forumUrl = "http://www.c2000.cn/dispbbs.asp?boardid="+ boradId +"&star="+ page +"&replyid="+ nextStartUserId +"&id="+ topId +"&skin=0&page="+ page;
        }

        Log.d("forumurl", forumUrl);

        StringRequest stringRequest = new StringRequest(forumUrl,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        String htmlData = Parse.getForumStr(response,page);

                        nextStartUserId = Parse.getNextStarUserId();
                        postUserId = (postUserId.length()==0)?Parse.getPostUserId():postUserId;

                        if(page==1)
                        maxpage = Parse.getForumMaxPage();

                        spage.setText(page + "/" + maxpage);

                        //处理引用回复
                        WebViewClient myWebViewClient = new WebViewClient() {
                            @Override
                            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                                if(url.trim().toLowerCase().contains("quota://")) {
                                    //Toast.makeText(DisplayMessageActivity.this,url,Toast.LENGTH_SHORT).show();
                                    //对引用回复做处理
                                    url = url.replace("quota://","");
                                    int idx = 0,seq = 0,st = 0;

                                    idx = url.indexOf("||||||");

                                    while (idx>0) {
                                        tempStr = url.substring(st, idx);
                                        st = idx;
                                        idx = url.indexOf("||||||",idx + 1);
                                        tempStr = tempStr.replace("||||||","");

                                        switch (seq) {
                                            case 0:
                                                try {
                                                    tempStr = java.net.URLDecoder.decode(tempStr,"utf-8");
                                                } catch (Exception e) {
                                                    e.printStackTrace();
                                                }
                                                quotaStr = "<div class=\"quote\"><b>以下是引用<i>" + tempStr + "</i>在";
                                                //点击执行引用回复处理
                                                sReplyContent.setHint("[引用 " + tempStr + " ]");
                                                break;
                                            case 1:
                                                quotaStr = quotaStr + tempStr + "的发言</b><br>";
                                                break;
                                            case 2: //处理引用回复的内容
                                                //Toast.makeText(DisplayMessageActivity.this,tempStr,Toast.LENGTH_SHORT).show();

                                                byte [] decode = Base64.decode(tempStr.getBytes(), Base64.DEFAULT);
                                                tempStr = new String(decode);
                                                Toast.makeText(DisplayMessageActivity.this,tempStr,Toast.LENGTH_SHORT).show();

                                                quotaStr = quotaStr + tempStr + "</div>";
                                                break;
                                        }

                                        seq++;
                                    }

                                    return true;
                                } else {
                                    return super.shouldOverrideUrlLoading(view, url);

                                }

                            }
                        };


                        webView.getSettings().setJavaScriptEnabled(true);
                        //webView.getSettings().setP
                        webView.setWebChromeClient(new WebChromeClient());
                        webView.setWebViewClient(myWebViewClient);
                        webView.loadDataWithBaseURL(null, htmlData, "text/html", "utf-8", null);
                        //webView.sh;

                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("TAG", error.getMessage(), error);
            }


        }){
            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                String str = null;
                try {
                    str = new String(response.data, "gbk");//这里写死不好哦
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return Response.success(str, HttpHeaderParser.parseCacheHeaders(response));
            }
        };

        quence.add(stringRequest);

    }

    //获取图片返回事件
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Log.d("requestCode", requestCode+"");
        Log.d("resultCode", resultCode + "");

        switch(requestCode) {
            case REQUEST_IMAGE:
                if(resultCode == RESULT_OK){
                    // Get the result list of select image paths
                    tmpPath = data.getStringArrayListExtra(ImageSelectorActivity.EXTRA_RESULT);
                    Log.d("tmpPath.size()",tmpPath.size()+"");
                    Log.d("result",path.size()+"");

                    // 添加入path list当中
                    int i = 0,j = 0;
                    for(i=0;i<tmpPath.size();i++) {
                        Log.d("i>>>",i+"");
                        Log.d("j>>>",j+"");
                        Log.d("path1>>>",path.size()+"");
                        if(i==0) {
                            j = path.size();
                            path.set(j-1,tmpPath.get(i));
                            //sAdapter.insert(tmpPath.get(i),j-1);
                        } else {
                            path.add(tmpPath.get(i));
                            //sAdapter.add(tmpPath.get(i));
                        }
                    }
                    Log.d("path2>>>",path.size()+"");
                    //判断所选图片是否已经超过限制值,若无超过，则显示+号，可以继续选择
                    if(path.size()<tcount) {
                        path.add("default");
                        
                        //sAdapter.add("default");
                    }
                    for (int k= 0  ; k< path.size() ; k++){
                        Log.d("path>>>",k+">>" + path.get(k));
                    }
                    //更新显示选择的图片
                    sAdapter.notifyDataSetChanged();

                }
                break;
            case TAKE_PICTURE:
                if(resultCode == RESULT_OK) { //启动裁剪程序
                    Intent intent = new Intent("com.android.camera.action.CROP");
                    intent.setDataAndType(imageUri,"image/*");
                    intent.putExtra("scale", true);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
                    startActivityForResult(intent, CROP_PICTURE);
                }
                break;
            case CROP_PICTURE:
                if(resultCode == RESULT_OK) {
                    Log.d("croppictureok","vvv");

                    int j = path.size();

                    //path.set(j - 1, outputImage.getAbsolutePath());
                    sAdapter.insert(outputImage.getAbsolutePath(),j-1);
                    sAdapter.remove("default");
                    if(j<tcount) {
                        path.add("default");
                    }

                    for(int i=0;i<path.size();i++) {
                        Log.d("pathimage:",path.get(i));
                    }
                    sAdapter.notifyDataSetChanged();
                }
                break;
            case REQUEST_LOGIN:
                if(resultCode == RESULT_OK) {
                    Toast.makeText(DisplayMessageActivity.this,"登录成功",Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    private void startUpload() {

        //mTaskList = new ArrayList<MyUploadImageThread>(tcount);
        final UploadManager uploadManager;

        Log.d("pathsize",path.size()+"");

        //初始化七牛云
        Configuration qnconfig = new Configuration.Builder()
                .chunkSize(256 * 1024)  //分片上传时，每片的大小。 默认 256K
                .putThreshhold(512 * 1024)  // 启用分片上传阀值。默认 512K
                .connectTimeout(10) // 链接超时。默认 10秒
                .responseTimeout(60) // 服务器响应超时。默认 60秒
                        //.recorder(recorder)  // recorder 分片上传时，已上传片记录器。默认 null
                        //.recorder(recorder, keyGen)  // keyGen 分片上传时，生成标识符，用于片记录器区分是那个文件的上传记录
                .zone(Zone.zone0) // 设置区域，指定不同区域的上传域名、备用域名、备用IP。默认 Zone.zone0
                .build();

        // 重用 uploadManager。一般地，只需要创建一个 uploadManager 对象
        uploadManager = new UploadManager(qnconfig);
        //先获取uploadtoken
        quence = Rserver.getRequestQueue(getApplicationContext());
        String url = "http://202.105.21.250:12580/index.php";

        final String[] uInfo = new String[4];


        StringRequest stringRequest = new StringRequest(url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        uInfo[0] = response;
                        uInfo[2] = (path.size() -1) +"";
                        for(i=0;i<path.size()-1;i++) {
                            uFileName = myUtil.getShared("userName") + "_" + String.valueOf(System.currentTimeMillis());
                            uploadManager.put(path.get(i), uFileName, response,
                                    new UpCompletionHandler() {
                                        @Override
                                        public void complete(String key, ResponseInfo info, JSONObject res) {
                                            //  res 包含hash、key等信息，具体字段取决于上传策略的设置
                                            Log.i("qiniu", key + ",\r\n " + info + ",\r\n " + res);
                                            //uPath.add("http://7xpdyg.com1.z0.glb.clouddn.com/" + key);
                                            uPath.put(key, "http://7xpdyg.com1.z0.glb.clouddn.com/" + key);

                                            if(uPath.size() == ( path.size() - 1 )) {
                                                mProgressDialog.dismiss();
                                                submitReply();
                                            }
                                        }


                                    },
                                    new UploadOptions(null, null, false,
                                            new UpProgressHandler(){
                                                public void progress(String key, double percent){
                                                    //publishProgress((int)percent*100); // 更新进度条
                                                    Log.i("qiniu", key + ": " + percent);
                                                }
                                            }, null)
                            );

                        }

                        Log.d("tokenget",TokenString);
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("TAG", error.getMessage(), error);
            }


        });

        quence.add(stringRequest);

    }

    public boolean  submitReply() {
        quence = Rserver.getRequestQueue(getApplicationContext());
        String url = "http://www.c2000.cn/savepost.asp?action=sre&method=fastreply&BoardID=1";

        StringRequest stringRequest = new StringRequest(Request.Method.POST,url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        //判断是否发表成功
                        if(response.indexOf("您尚未登录，您可以输入您的用户名、密码登录以便进行您的操作")!=-1) {
                            Toast.makeText(DisplayMessageActivity.this,"发表回复失败，需重新登录",Toast.LENGTH_SHORT).show();
                            myUtil.saveShared("isLogin","notlogin");
                            Intent intent = new Intent(DisplayMessageActivity.this, UserLoginActivity.class);
                            startActivityForResult(intent, REQUEST_LOGIN);

                        } else if (response.indexOf("保存回复成功")!=-1) {
                            path.clear();
                            uPath.clear();
                            if(path.size()==0) path.add("default");
                            sAdapter.notifyDataSetChanged();
                            mGridView.setVisibility(View.GONE);
                            Toast.makeText(DisplayMessageActivity.this,"发表回复成功",Toast.LENGTH_SHORT).show();
                            sReplyContent.setText("");

                            //清空引用内容
                            if(quotaStr.length()>0) {
                                quotaStr = "";
                                sReplyContent.setText(R.string.pleasereply);
                            }

                        }

                        Log.d("replyget", response);
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("TAG", error.getMessage(), error);
            }

        }){

            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                String str = null;
                String cookieStr = null;

                try {
                    str = new String(response.data, "gbk");//这里写死不好哦
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return Response.success(str, HttpHeaderParser.parseCacheHeaders(response));
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                String cookieStr = null;
                cookieStr = myUtil.getShared("cookie");

                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("Host", "www.c2000.cn");
                headers.put("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
                headers.put("Origin","http://www.c2000.cn");
                headers.put("Upgrade-Insecure-Requests","1");
                //headers.put("Content-Type", "application/x-www-form-urlencoded");
                headers.put("Referer","http://www.c2000.cn/dispbbs.asp?boardid=1&star=17&replyid=3366084&id=2911373&skin=0&page=1");
                headers.put("Accept-Encoding","gzip, deflate");
                headers.put("Cookie",cookieStr);
                return headers;
            }

            @Override
            protected String getParamsEncoding() {
                return "gbk";
            }

            @Override
            protected Map<String, String> getParams() {
                //在这里设置需要post的参数
                Map<String, String> map = new HashMap<String, String>();
                map.put("passwd", "%7B%24memberword%7D");
                map.put("followup",postUserId);
                map.put("RootID",topId);
                map.put("star","17");
                try {
                    String imgContent = "";
                    //增加图片上传
                    if(uPath.size()>0) {
                        imgContent = "<div style='clear:both'></div>";

                        for(String keyValue:uPath.values()) {
                            imgContent = imgContent + "<img src=\""+ keyValue + "\">";
                            //"<a href='"+ keyValue +"' target='_blank' id='ImgSpan'><img src='" + keyValue + "' border='0' alt='点击看大图' onmousewheel='return bbimg(this)' onload=\"javascript:if(this.width>screen.width-333)this.style.width=screen.width-333;\"/></a>" ;
                        }
                    }
                    replyContent = quotaStr + sReplyContent.getText().toString() + imgContent;

                    map.put("Body", replyContent);
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.d("encodeerror",e.getMessage());
                }
                map.put("TotalUseTable","Dv_bbs4");
                map.put("UserName",myUtil.getShared("userName"));
                map.put("ShowFacePage","1");
                map.put("signflag","yes");
                map.put("Submit","OK%21%B7%A2%B1%ED%BB%D8%B8%B4");
                return map;
            }
        };

        quence.add(stringRequest);
        return true;
    }

    /*
    * 处理分页popupwindow的处理函数
    * */
    private void guickSelectPage() {
        final View popView = getLayoutInflater().inflate(R.layout.forum_select_page, null);
        popSpage = new PopupWindow(DisplayMessageActivity.this);
        final int tempPage = page;

        Log.d("spage","isclick");

        //处理直接跳转到首页，尾页
        sFirstPage = (Button)popView.findViewById(R.id.sfirstpage);
        sMaxPage = (Button)popView.findViewById(R.id.smaxpage);
        sSelectCancel = (Button)popView.findViewById(R.id.sselectcancel);
        sSelectOk = (Button)popView.findViewById(R.id.sselectok);

        sFirstPage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                page = 1;getPageContent();popSpage.dismiss();
            }
        });
        sMaxPage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                page = maxpage;
                getPageContent();
                popSpage.dismiss();
            }
        });
        sSelectOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(tempPage != page) getPageContent();
                popSpage.dismiss();
            }
        });
        sSelectCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popSpage.dismiss();
            }
        });

        //绑定页数
        mPagePicker = (NumberPicker) popView.findViewById(R.id.show_select_page);
        //mPagePicker.setFormatter(this);
        //mPagePicker.setOnValueChangedListener();
        //mPagePicker.setOnScrollListener(this);
        mPagePicker.setMaxValue(maxpage);
        mPagePicker.setMinValue(1);
        mPagePicker.setValue(page);
        mPagePicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker numberPicker, int i, int i1) {
                page = i1;
                //popSpage.dismiss();
            }
        });

        popSpage.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
        popSpage.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
        popSpage.setFocusable(true);
        popSpage.setOutsideTouchable(true);
        popSpage.setContentView(popView);

        //关闭popupwindow时候才更新pagecontent
        //popSpage.setOnDismissListener(new PopupWindow.OnDismissListener() {
        //    @Override
        //    public void onDismiss() {
        //        if(tempPage != page)
        //            getPageContent();
        //    }
        //});

        popSpage.showAtLocation(parentView, Gravity.BOTTOM, 0, 0);
    }


}

